const labelService = require("../service/label.service");

const verifyLabelExists = async (ctx, next) => {
  try {
    // 1、获取客户端传递过来的label
    const { labels } = ctx.request.body;

    // 2、判断所有的labels中的name是否已经存在于labels表中
    let newLabels = [];
    for (const name of labels) {
      const [result] = await labelService.queryLabelByName(name);
      const labelObj = { name };
      if (result) {
        // 获取name对应的label的id
        labelObj.id = result.id;
      } else {
        // 插入name，并且获取插入后的id
        const insertResult = await labelService.create(name);
        labelObj.id = insertResult.insertId;
      }
      newLabels.push(labelObj);
    }

    // 3、打印所有labels，且存储起来，传递下去
    // console.log(newLabels);
    ctx.labels = newLabels;
  } catch (error) {
    console.log(error);
  }

  await next();
};

module.exports = { verifyLabelExists };
